/*
 *  Copyright 2022/5/25 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.asialjim.encommunicate.rsa.management.controller;

import com.asialjim.encommunicate.base.rsa.key.RSAClientKey;
import com.asialjim.encommunicate.rsa.management.pojo.AppEnDecryptInfo;
import com.asialjim.encommunicate.rsa.management.pojo.RSAKeyResult;
import com.asialjim.encommunicate.rsa.management.service.RSAGenerateService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;
import java.util.stream.Stream;

/**
 * <h2> RSAManagementController </h2>
 * <p> RSA 密钥对管理
 * </strong><p><p>Copyright &copy; Asial Jim Co., LTD
 *
 * @author <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 * @version 1.0
 * @since 2023/2/27 &nbsp;&nbsp; 1.0 &nbsp;&nbsp; JDK 17
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/security/keys")
public class RSAManagementController {
    @Resource private RSAGenerateService rsaGenerateService;

    @GetMapping("/client/{appid}/{keySize}")
    public RSAKeyResult<RSAClientKey> rsaKey(@PathVariable("appid") String appid, @PathVariable("keySize") Integer keySize, @RequestParam String name,
                                             @RequestHeader String user, @RequestHeader String passwd) {

        try {
            if (checkUser(user, passwd, "genKey"))
                return RSAKeyResult.<RSAClientKey>builder().code("401").msg("Request Forbidden").errList(Stream.of("权限不足").toList()).build();

            RSAClientKey rsaClientKey = rsaGenerateService.generateClientKey(appid, keySize, name);
            return RSAKeyResult.<RSAClientKey>builder().code("0").msg("OK").data(rsaClientKey).errList(Stream.of("请谨慎保存此密钥对").toList()).build();
        } catch (Throwable t) {
            return RSAKeyResult.<RSAClientKey>builder().code("401").msg("Request Forbidden").errList(Stream.of(t.getMessage()).toList()).build();
        }
    }

    @GetMapping("/client/{appid}")
    public RSAKeyResult<RSAClientKey> clientKey(@PathVariable String appid, @RequestHeader String user, @RequestHeader String passwd) {
        if (checkUser(user, passwd, "clientKey"))
            return RSAKeyResult.<RSAClientKey>builder().code("401").msg("Request Forbidden").errList(Stream.of("权限不足").toList()).build();

        RSAClientKey clientKey = rsaGenerateService.generateClientKey(appid);
        return RSAKeyResult.<RSAClientKey>builder().code("0").msg("OK").data(clientKey).errList(Stream.of("请谨慎保存此密钥对").toList()).build();
    }

    @GetMapping("/infos")
    public RSAKeyResult<Set<AppEnDecryptInfo>> allInfos(@RequestHeader String user, @RequestHeader String passwd) {
        if (checkUser(user, passwd, "allKeys"))
            return RSAKeyResult.<Set<AppEnDecryptInfo>>builder().code("401").msg("Request Forbidden").errList(Stream.of("权限不足").toList()).build();

        return RSAKeyResult.<Set<AppEnDecryptInfo>>builder().code("0").msg("OK").data(rsaGenerateService.infos()).build();
    }

    @PostMapping("/infos")
    public RSAKeyResult<Set<AppEnDecryptInfo>> modify(@RequestHeader String user, @RequestHeader String passwd, @RequestBody @Valid AppEnDecryptInfo body){
        if (checkUser(user, passwd, "modify"))
            return RSAKeyResult.<Set<AppEnDecryptInfo>>builder().code("401").msg("Request Forbidden").errList(Stream.of("权限不足").toList()).build();

        Set<AppEnDecryptInfo> infos = rsaGenerateService.modify(body);
        return RSAKeyResult.<Set<AppEnDecryptInfo>>builder().code("0").msg("OK").data(infos).build();
    }

    private boolean checkUser(String user, String passwd, String type) {
        if (StringUtils.isAnyBlank(user, passwd))
            return true;

        if (!checkPasswd(user,passwd))
            return true;

        switch (type){
            case "genKey":// 生成密钥
                break;
            case "clientKey":// 查询客户端密钥
                break;
            case "allKeys":// 查询所有密钥对
                break;
            case "modify":// 修改应用配置
                break;
            default:
        }

        // TODO 用户密码检查，当通过检查时，才可获取到客户端密钥对
        // TODO 当用户密码检查通过，则返回  true， 否则返回 false
        // TODO 判断用户是否具有业务权限
        log.info("获取客户端密钥对，user:{}, passwd:{}, 业务类型：{}", user, passwd, type);
        return false;
    }

    private boolean checkPasswd(String user, String passwd){
        // TODO 判断用户，密码是否匹配
        log.info("检查用户名:{}，密码：{} 匹配",user,passwd);
        return true;
    }
}